<template>
  <div class = "journal">
  <div class="journal-body">
    <div class="journal-header">
      <input v-model="diary.diaryName" placeholder="YOUR JOURNAL" />
    </div>
    <div v-if="place" class="journal-entry">
      <div class="images-container">
        <img :src="image" alt="地点照片"  class = "image" style="width: 264px;height: 400px;">
      </div>
      <div class="text">
        <h2 class = "title">{{ place?.placeName }}</h2>
        <p class = "date">Date: {{ formatDate(place?.visitTime)}}</p>
        <p class = "des">{{ place?.description }}</p>
        <div v-if="tags && tags.length > 0" class = "tags">
          <p class ="tag">{{ tags[0].tagName }} | {{ getMoodIcon(tags[0].moodName) }}</p> 
          <p class ="tag">{{ tags[1].tagName }} | {{ getMoodIcon(tags[1].moodName) }}</p>
        </div>
        <div v-else>
          标签加载中...
        </div>
      </div>
    </div>
    <div v-else>
      加载中...
    </div>
    <div class="button-container">
      <button @click="saveAsImage" class="button">保存为图像</button>
      <button @click="saveJournal" class="button">保存该手账</button>
    </div>
  </div>
  </div>
</template>

<script>
import html2canvas from "html2canvas";
import axios from "axios";
import router from "@/router";

export default {
  props: ['placeId'],
  data() {
    return {
      place: null,
      tags:null,
      image:null,
      emoticons: {
      '😄': '开心',
      '😢': '伤心',
      '😡': '愤怒',
      '😪': '沮丧',
      '🥱': '疲倦',
    },
    diary: {
      diaryName: '',
      userId: '',
      complete:''
      // 添加更多需要的字段
    }
    }
  },
  mounted() {
    console.log('Received placeId:', this.placeId);
    this.loadData();
    this.fetchTags();
    this.fetchImages();
  },
  methods: {
    loadData() {
  console.log('Fetching data for placeId:', this.placeId);  // 调试输出
  return new Promise((reject) => {
    const token = localStorage.getItem('userToken');
    axios.get(`/api/places/find`, {
      headers: {
        'Authorization': token
      },
      params: { placeId: this.placeId }
    }).then(response=>{
      this.place = response.data.data;
  })
    .catch(error => {
      console.error('Error loading data:', error);
      this.place = null;
      reject(error);
    });
  });
},
formatDate(value) {
    if (!value) return '';
    return value.split('T')[0];
    },
  saveAsImage() {
  console.log("Trying to save as image...");
  const element = this.$el.querySelector(".journal-body");
  if (element) {
    console.log("Element found, rendering canvas...");
    html2canvas(element, { logging: true, letterRendering: 1, useCORS: true }).then(canvas => {
      console.log("Canvas ready, preparing download...");
      const image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
      const link = document.createElement('a');
      link.download = 'journal-snapshot.png';
      link.href = image;
      link.click();
      link.remove();
      console.log("Download should now be starting...");
    }).catch(err => {
      console.error("Error creating canvas: ", err);
    });
  } else {
    console.error("Element not found in the DOM");
  }
},fetchTags() {
  console.log(`Fetching tags for placeId: ${this.placeId}`);
  axios.get(`/api/moods/getplacemood`, {
    params: {
      placeId: this.placeId 
    }
  })
  .then(response => {
    this.tags = response.data.data;
    console.log('Tags fetched successfully:', this.tags);
  }).catch(error => {
    console.error('获取标签数据时发生错误:', error);
    alert('加载标签数据失败，请稍后再试');
  });
},fetchImages(){
  axios.get('/api/images/byPlaceId',{
    params:{
      placeId:this.placeId,
    }
  }).then(response=>{
    this.image = response.data.data[0].imageUrl
  })
  .catch(error=>
    {
      console.error('失败再试一次：',error);
      alert("加载图片数据失败，再试一次")
    }
  )
},
getMoodIcon(moodName) {
    switch (moodName) {
      case '开心':
        return '😀';
      case '伤心':
        return '😢';
      case '愤怒':
        return '😡';
      case '沮丧':
        return '😪';
      case '疲倦':
        return '🥱';
      default:
        return moodName;
    }
  },
saveJournal() {
    const diary = this.diary;
    diary.complete = true;
    diary.diaryName = this.place.placeName;
    axios.post('/api/diarys/add', diary, {
        headers: {
            'Authorization': localStorage.getItem('userToken') // Authentication token
        },
        params:{
          placeId:this.placeId
        }
    })
.then(response => {
    alert('手账已成功保存!');
    console.log(response.data.data);
    router.push('/overview');
})
.catch(error => {
    this.$message.error('保存手账时发生错误: ' + error.message);
});
}


}}
</script>

<style>
@import "@/assets/css/jounal1.css";
</style>